<?php

namespace App\Services\SetGoldBudget;

use Carbon\Carbon;
use App\Models\User;
use App\Models\GoldRound;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class SetGoldBudgetRequest extends FormRequest
{
	public function rules()
	{
		if (!$this->user()->pay_code) {
			fail('请先设置交易密码');
		}

		return [
			'rid' => [
				'required',
				'integer',
				'min:1',
			],
			'budget' => [
				'required',
				'numeric',
				'digits_between:3,6',
				'between:100,100000',
				$this->budget(),
			],
			'pay_code' => $this->payCode(false)
		];
	}

	public function attributes()
	{
		return [
			'rid' => '场次',
			'budget' => '抢购预算',
			'budget.digits_between' => '抢购预算必须是介于3~6位的整数',
			'pay_code' => '交易密码'
		];
	}

	public function budget()
	{
		return function ($key, $value, $fail) {

			/**
			 * @var User $user
			 */
			$user = $this->user();


			$rid = $this->rid;

			$time = Carbon::now();

			if ($time->lt(GoldRound::todayOpenedAt($rid))) {
				return $fail('本场尚未开场');
			} elseif ($time->gte(GoldRound::todayStartedAt($rid))
				and $time->lte(GoldRound::todayEndedAt($rid))) {
				return $fail('抢购中不可操作');
			} elseif ($time->gt(GoldRound::todayEndedAt($rid))) {
				return $fail('本场已经结束');
			} elseif (! $user->isValidVip()) {
				return $fail('仅有效VIP会员可参与黄金风暴');
			} elseif (! $this->isBudgetMatched($value)) {
				return $fail('抢购预算必须是100的倍数');
			} elseif ($rid == 3 and $value < 500) {
				return $fail('高级场预算500元起');
			} elseif (! $this->isGoldBeansEnough($value)) {
				return $fail('金豆不足请咨询推荐人');
			}

			return true;
		};
	}

	protected function isBudgetMatched($budget)
	{
		return big_decimal($budget)->remainder(100)->isZero();
	}

	protected function isGoldBeansEnough($budget)
	{
		$needBeans = big_decimal($budget)->multipliedBy(0.06);
		return $this->user()->isGoldBeansEnough($needBeans);
	}
}
